package com.itheima.tanhua.dubbo.mongo.api.impl;

import com.itheima.tanhua.api.FocusUserApi;
import com.itheima.tanhua.mongo.FocusUser;
import com.mongodb.client.result.DeleteResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

/**
 * @author Lff
 * @date 2022/4/4
 */
@DubboService
public class FocusUserApiImpl implements FocusUserApi {

    @Autowired
    private MongoTemplate mongo;

    /**
     * 查看是否关注
     *
     * @param userId
     * @param followUserId
     * @return
     */
    @Override
    public boolean hasFocus(Long userId, Long followUserId) {
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("followUserId").is(followUserId));
        return mongo.exists(query, FocusUser.class);
    }

    /**
     * 用户关注列表
     *
     * @param focusUser
     * @return
     */
    @Override
    public String save(FocusUser focusUser) {
        try {
            //获取id
            ObjectId objectId = ObjectId.get();
            focusUser.setId(objectId);
            mongo.save(focusUser);
            return objectId.toHexString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 删除记录 根据userId和followUserId
     */
    @Override
    public boolean delete(Long userId, Long followUserId) {
        try {
            Query query = Query.query(Criteria.where("userId").is(userId)
                    .and("followUserId").is(followUserId));
            mongo.remove(query, FocusUser.class);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
